﻿// <copyright file="NamespaceClassReport.aspx.cs">
// Copyright (c) 2009 All Right Reserved
// </copyright>
// <author>Yuvaraj Ilangovan</author>
// <date>2009-07-14</date>
// <summary>Contains UI logic for showing code coverage aggregate report for Namespace level</summary>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RepRef;
using System.Data;
using System.Collections;
using System.Configuration;

public partial class ContentPages_NamespaceClassReport : System.Web.UI.Page
{
    RepRef.IsimpleWcfClient aggrProxy;
    RepRef.StatisticsReport ststReport;
    RepRef.ModuleManager mgr;
    string strXMLPath;
    public static bool showImage = false;
    private string _xmlPath = string.Empty;
    public string ProjectName
    {
        get
        {
            string _projName = string.Empty;
            if (Session["ProjName"] != null)
            {
                _projName = Convert.ToString(Session["ProjName"]);
            }
            else
            {
                _projName = ConfigurationManager.AppSettings["ProjName"].ToString();
            }
            return _projName;
        }
    }

    public string XMLPath
    {        
        get
        {
            if (Session["RptXMLPath"] != null)
            {
                _xmlPath = Session["RptXMLPath"].ToString();
            }
            return _xmlPath; 
        }   
     
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        lblprojName.Text = this.ProjectName; 
        if (!IsPostBack)
        {
            if (Session["RptXMLPath"] != null)
            {
                strXMLPath = Session["RptXMLPath"].ToString();
            }
            if ((!string.IsNullOrEmpty(Request.QueryString["nName"])) && (!string.IsNullOrEmpty(Request.QueryString["mod1"])))
            {
                LoadNamesLevelStatistics(Request.QueryString["mod1"].ToString(), Request.QueryString["nName"].ToString(), strXMLPath);
                LoadNamesLevelClsAggregate(Request.QueryString["mod1"].ToString(), Request.QueryString["nName"].ToString(), strXMLPath);
                LoadNamesLevelClassesReport(Request.QueryString["mod1"].ToString(), Request.QueryString["nName"].ToString(), strXMLPath);
            }
        }
    }

    protected void LoadNamesLevelStatistics(string modName, string nsName, string strXMLPath)
    {
        try
        {
            aggrProxy = new IsimpleWcfClient();
            mgr = aggrProxy.ParseXmlObject(strXMLPath);
            ststReport = aggrProxy.GetStateticsByNameSpace(modName, nsName, strXMLPath);           
            lblCovLines.Text = ststReport.LOC.ToString();
            lblParCovLines.Text = ststReport.PLOC.ToString();
            lblCovBlocks.Text = ststReport.BlocksCov.ToString();
            lblNCLines.Text = ststReport.NCLOC.ToString();
            lblNCBlocks.Text = ststReport.BlocksNt.ToString();
            lblStatsName.Text = ststReport.Name;
            lblCovClasses.Text = ststReport.TotClsCov.ToString();
            lblNClasses.Text = ststReport.TotNClsCov.ToString();
            lblMethodsPerClass.Text = string.Format("{0:#.##}", ststReport.AvgMtdClass);
            lblTime.Text = mgr.FileCreationTime.ToString();
        }
        catch (Exception ex)
        {

        }
    }

    protected void LoadNamesLevelClsAggregate(string modName, string nsName, string strXMLPath)
    {
        try
        {
            IList<RepRef.NamespaceClassInfoAggr> nsInfoCollection;
            aggrProxy = new IsimpleWcfClient();
            mgr = aggrProxy.ParseXmlObject(strXMLPath);
            nsInfoCollection = aggrProxy.GetNmsLvlClassAggReport(modName, nsName, strXMLPath);
            gvNsLvlClsCovAggregate.DataSource = nsInfoCollection;
            gvNsLvlClsCovAggregate.DataBind();
        }
        catch (Exception ex)
        {
        }

    }
    protected void LoadNamesLevelClassesReport(string modName, string nsName, string strXMLPath)
    {
        try
        {
            IList<RepRef.ClassInfo> nsclsInfoCollection;
            aggrProxy = new IsimpleWcfClient();
            mgr = aggrProxy.ParseXmlObject(strXMLPath);
            nsclsInfoCollection = aggrProxy.GetNmsLvlClassReport(modName, nsName, strXMLPath);
            DataTable dtTable = CreateDataTable(nsclsInfoCollection);
            Session["NsDataTable"] = dtTable;
            DataView dv = new DataView(dtTable);
            dv.Sort = "CovPercentage ASC";
            gvNmsLvlClassesReport.DataSource = dv;
            gvNmsLvlClassesReport.DataBind();
        }
        catch (Exception ex)
        {
        }
    }

    public string TruncateDouble(double dblValue)
    {
        string strPercent = string.Format("{0:0.##}", dblValue);
        return strPercent + "%";
    }
    public int SetLblMajorWidth(double dblValue)
    {
        int major = Convert.ToInt32(Math.Round(dblValue));
        return major;
    }
    public int SetLblMinorWidth(double dblValue)
    {
        int minor = (100 - (Convert.ToInt32(Math.Round(dblValue))));
        return minor; 
    }
    protected void gvNsLvlClsCovAggregate_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        string strPath = string.Empty;
        switch (e.CommandName)
        {
            case "OpenCloud":
                int rowIndex;
                if (int.TryParse(e.CommandArgument.ToString(), out rowIndex))
                {
                    if (Session["RptXMLPath"] != null)
                    {
                        strXMLPath = Session["RptXMLPath"].ToString();
                    }

                    if (!string.IsNullOrEmpty(Request.QueryString["nName"]))
                    {
                        strPath = "../ContentPages/CoverageCloud.aspx?modname=" + Request.QueryString["mod1"].ToString() + "&nName=" + Request.QueryString["nName"].ToString() + "&rptLink=" + strXMLPath;
                    }

                    //Server.Transfer(strPath);
                    Response.Redirect(strPath);

                }
                break;
        }

    }
    protected void AddSortImage(GridViewRow HeaderRow, int colIndex)
    {
        Image sortImage = new Image();
        sortImage.CssClass = "SortImageStyle";
        //ViewState["SortDirection"] = GetSortDirection(column);
        if (showImage) // this is a boolean variable which should be false 
        {            //  on page load so that image wont show up initially.


            if (ViewState["SortDirection"] != null)
            {
                if (ViewState["SortDirection"].ToString() == "ASC")
                {

                    sortImage.ImageUrl = "/CoverageReport/App_Themes/ReportThemes/images/White_GrayDown.png";
                    sortImage.AlternateText = " Ascending Order";
                }

                else
                {
                    sortImage.ImageUrl = "/CoverageReport/App_Themes/ReportThemes/images/White_GrayUp.png";
                    sortImage.AlternateText = " Descending Order";
                }

                HeaderRow.Cells[colIndex].Controls.Add(sortImage);
            }
        }

    }
    private string GetSortDirection(string column)
    {

        // By default, set the sort direction to ascending.
        string sortDirection = "ASC";

        // Retrieve the last column that was sorted.
        string sortExpression = ViewState["SortExpression"] as string;

        if (sortExpression != null)
        {
            // Check if the same column is being sorted.
            // Otherwise, the default value can be returned.
            if (sortExpression == column)
            {
                string lastDirection = ViewState["SortDirection"] as string;
                if ((lastDirection != null) && (lastDirection == "ASC"))
                {
                    sortDirection = "DESC";
                }
            }
        }

        // Save new values in ViewState.
        ViewState["SortDirection"] = sortDirection;
        showImage = true;
        ViewState["SortExpression"] = column;

        return sortDirection;
    }

    private DataTable CreateDataTable(IList<ClassInfo> clsInfoColln)
    {
        DataTable dtTable = new DataTable();
        dtTable.Columns.Add("ModuleName", typeof(string));
        dtTable.Columns.Add("NamespaceName", typeof(string));
        dtTable.Columns.Add("Classname", typeof(string));
        dtTable.Columns.Add("CovPercentage", typeof(double));
        dtTable.Columns.Add("AvgLnsMtd", typeof(double));


        foreach (ClassInfo clsInfo in clsInfoColln)
        {
            DataRow dtRow = dtTable.NewRow();
            dtRow["ModuleName"] = clsInfo.ModuleName;
            dtRow["NamespaceName"] = clsInfo.NamespaceName;
            dtRow["Classname"] = clsInfo.Classname;
            dtRow["CovPercentage"] = clsInfo.CovPercentage;
            dtRow["AvgLnsMtd"] = clsInfo.AvgLnsMtd;

            dtTable.Rows.Add(dtRow);
        }
        return dtTable;
    }
    protected void gvNmsLvlClassesReport_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (Session["NsDataTable"] != null)
        {
            DataTable dtTable = (DataTable)Session["NsDataTable"];
            if (dtTable != null)
            {
                dtTable.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
                gvNmsLvlClassesReport.DataSource = dtTable;
                gvNmsLvlClassesReport.DataBind();
            }
        }
    }
    protected void gvNmsLvlClassesReport_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        //sortColumnIndex = GetSortColumnIndex();
        {
            string sortExprn = string.Empty;
            if (ViewState["SortExpression"] != null)
            {
                sortExprn = ViewState["SortExpression"].ToString();
            }
            int index = findColumnIndex(sortExprn);
            AddSortImage(e.Row, index);


        }
    }
    private int findColumnIndex(string accessibleHeaderText)
    {
        for (int index = 0; index < gvNmsLvlClassesReport.Columns.Count; index++)
        {
            if (String.Compare(gvNmsLvlClassesReport.Columns[index].SortExpression, accessibleHeaderText, true) == 0)
            {
                return index;
            }
        }
        return -1;
    }
    protected void gvNmsLvlClassesReport_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lbl = ((Label)e.Row.FindControl("lbltotcov"));
            System.Web.UI.HtmlControls.HtmlTableCell TCell = ((System.Web.UI.HtmlControls.HtmlTableCell)e.Row.FindControl("tdTotCov"));
            string[] strArr = null;
            if (!string.IsNullOrEmpty(lbl.Text))
            {
                strArr = lbl.Text.Split('%');
                if (Convert.ToDouble(strArr[0].ToString()) < 75.0)
                {
                    TCell.BgColor = "#FF0000";

                }
            }
        }
    }
    protected void gvNsLvlClsCovAggregate_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblns = ((Label)e.Row.FindControl("lblNmsName"));
            Label lblcov = ((Label)e.Row.FindControl("lbltotcov"));
            ImageButton img = ((ImageButton)e.Row.FindControl("imgCloud"));
            if (!string.IsNullOrEmpty(lblns.Text))
            {
                img.ToolTip = "Tag cloud report for " + lblns.Text;
            }
            System.Web.UI.HtmlControls.HtmlTableCell TCell = ((System.Web.UI.HtmlControls.HtmlTableCell)e.Row.FindControl("totalCover"));
            string[] strArr = null;
            if (!string.IsNullOrEmpty(lblcov.Text))
            {
                strArr = lblcov.Text.Split('%');
                if (Convert.ToDouble(strArr[0].ToString()) < 75.0)
                {
                    TCell.BgColor = "#FF0000";
                }
            }
        }
    }
    protected string TruncateFewCharacters(string MethodName)
    {
        string properString = string.Empty;
        properString = MethodName.Replace("<", "&lt");
        properString = properString.Replace(">", "&gt");
        return WrappableText(properString);
    }
    protected static string WrappableText(string source)
    {
        //string nwln = Environment.NewLine;
        //string modString = "<p>" +
        //    source.Replace(nwln + nwln, "</p><p>")
        //    .Replace(nwln, "<br />") + "</p>";

        if (source.Length > 75)
        {
            string strTemp = source.Substring(0, 75);
            return strTemp + "<b> ...</b>";
        }
        else
        {
            return source;
        }

    }


    



}
